<?php
namespace app\admin\middleware;

use app\admin\jwt\MyJwt;
use app\admin\lib\exception\BaseException;
use Closure;
use think\Request;

class Token
{
    public function handle(Request $request, Closure $next)
    {
        $authHeader = $request->header('token');

        if (empty($authHeader)) {
            throw new BaseException([
                'code' => 401,
                'message' => '缺少认证令牌',
                'errorCode' => 10014
            ]);
        }

        // 检查token格式，允许没有Bearer前缀的情况
        if (preg_match('/^Bearer\s+(.+)$/i', $authHeader, $matches)) {
            $token = $matches[1];
        } else {
            // 如果没有Bearer前缀，直接使用整个值作为token
            $token = $authHeader;
        }

        if (empty($token)) {
            throw new BaseException([
                'code' => 401,
                'message' => '令牌格式错误',
                'errorCode' => 10015
            ]);
        }

        try {
            $payload = MyJwt::checkToken($token);
            $request->user = $payload;
            return $next($request);
        } catch (BaseException $e) {
            throw $e; // 直接抛出原始异常，保留原始错误信息
        }
    }
}